package com.lenovo.smarttraffic.ui.activity.stage2;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.CarInfo;
import com.lenovo.smarttraffic.database.BalanceByCarNumber;
import com.lenovo.smarttraffic.database.RechargeRecord;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;

import org.litepal.LitePal;

import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class AllRechargeActivity extends BaseActivity implements View.OnClickListener {

    private Gson gson = new Gson();

    private TextView car_number;
    private EditText money_et;
    private Button charge_btn;
    private Button cancel_btn;

    private List<CarInfo.ROWSDETAILBean> batchRecharge;

    private int pos = -1;

    @Override
    protected int getLayout() {
        return R.layout.activity_all_charge;
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        batchRecharge = gson.fromJson(getIntent().getStringExtra("carInfo"),
                new TypeToken<List<CarInfo.ROWSDETAILBean>>() {
                }.getType());

        pos = -1;

        try {
            pos = getIntent().getExtras().getInt("pos");
        } catch (Exception e) {
            e.printStackTrace();
        }


        initView();
        initData();
        initEvent();
    }

    private void initEvent() {
        cancel_btn.setOnClickListener(this);
        charge_btn.setOnClickListener(this);
    }

    private void initData() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < batchRecharge.size(); i++) {
            stringBuilder.append(batchRecharge.get(i).getCarnumber()).append("\n");
        }
        car_number.setText(stringBuilder.toString());
        stringBuilder.delete(0, stringBuilder.length());
    }

    private void initView() {
        car_number = findViewById(R.id.car_number);
        money_et = findViewById(R.id.monet_et);
        charge_btn = findViewById(R.id.btn_charge);
        cancel_btn = findViewById(R.id.btn_cancel);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_charge:
                doRecharge(v);
                break;
            case R.id.btn_cancel:
                finish();
                break;
        }
    }

    private void doRecharge(View v) {
        int money = Utils.parseInt(money_et.getText().toString());
        if (money != 0) {
            ProgressDialog progressDialog = new ProgressDialog(v.getContext());
            progressDialog.setTitle("请求状态");
            progressDialog.setMessage("网络请求中");
            progressDialog.setCancelable(false);
            progressDialog.show();

            //进行网络请求
            HttpUtils.post("get_all_user_info", new HttpUtils().setParam("UserName", MainActivity.userName),
                    response -> {
                        if (Utils.getResult(response)) {
                            ToastUtils.showToast(AllRechargeActivity.this, "网络请求成功", Toast.LENGTH_SHORT);
                            progressDialog.dismiss();
                            //进行充值，也就是对数据库进行改写
                            for (int i = 0; i < batchRecharge.size(); i++) {
                                CarInfo.ROWSDETAILBean rowsdetailBean = batchRecharge.get(i);
                                //查询有多少余额
                                BalanceByCarNumber balanceByCarNumber = LitePal.select("balance").where("carNumber = ?", rowsdetailBean.getCarnumber()).find(BalanceByCarNumber.class).get(0);
                                int balance = Utils.parseInt(balanceByCarNumber.getBalance());
                                String moneyAfterRecharge = String.valueOf(balance + money);
                                balanceByCarNumber.setBalance(moneyAfterRecharge);
                                balanceByCarNumber.save();
                                //保存充值记录
                                new RechargeRecord(new Date(),
                                        rowsdetailBean.getCarnumber(),
                                        money + "",
                                        moneyAfterRecharge,
                                        MainActivity.userName).save();

                                HttpUtils.post("set_car_account_recharge",
                                        new HttpUtils().setParam("CarId", pos > 0 ? pos : (rowsdetailBean.getNumber() - 100)).
                                                setParam("Money", money).
                                                setParam("UserName", MainActivity.userName),
                                        response2 -> {
                                            if (Utils.getResult(response2)) {
                                                Toast.makeText(this, "充值成功", Toast.LENGTH_SHORT).show();
                                                finish();
                                            } else {
                                                Toast.makeText(this, "充值失败", Toast.LENGTH_SHORT).show();
                                            }
                                        });
                            }
                        } else {
                            ToastUtils.showToast(AllRechargeActivity.this, "网络请求失败", Toast.LENGTH_SHORT);
                        }
                    });

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(() -> {
                        if (progressDialog.isShowing()) {
                            progressDialog.dismiss();
                            ToastUtils.showToast(AllRechargeActivity.this, "网络请求失败", Toast.LENGTH_SHORT);
                        }
                    });
                }
            }, 4000);

        } else {
            Toast.makeText(this, "不能充值0元", Toast.LENGTH_SHORT).show();
        }

    }
}
